package cn.signalpha.modules.shop.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.signalpha.common.cache.ConfigCache;
import cn.signalpha.common.cache.ConfigKeys;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.dto.ConfigDTO;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.com.entity.User;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.shop.dto.CouponDTO;
import cn.signalpha.modules.shop.entity.Coupon;
import cn.signalpha.modules.shop.entity.CouponUser;
import cn.signalpha.modules.shop.service.CouponService;
import cn.signalpha.modules.shop.service.CouponUserService;
import cn.signalpha.modules.shop.vo.CouponVO;
import cn.signalpha.modules.shop.wrapper.CouponWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author signalpha
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SHOP_NAME + "/wap/coupon")
@Api(value = "优惠券", tags = "优惠券")
public class ApiCouponController extends BaseController {

	private final UserService userService;
	private final CouponService couponService;
	private final CouponUserService couponUserService;

	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "sellerId", dataType = "string", value = "商户id，平台为0"),
		@ApiImplicitParam(name = "useType", dataType = "string", value = "使用类型"),
	})
	@ApiOperation(value = "优惠券列表", notes = "领券中心")
	public R<IPage<CouponVO>> page(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		IPage<Coupon> page = couponService.page(Condition.getPage(query), Wrappers.<Coupon>query().lambda()
			.eq(ObjectUtil.isNotEmpty(params.get("sellerId")), Coupon::getSellerId, params.get("sellerId"))
			.eq(ObjectUtil.isNotEmpty(params.get("useType")), Coupon::getUseType, params.get("useType"))
			.eq(Coupon::getType, 1).eq(Coupon::getStatus, 1).gt(Coupon::getLastTotal, 0)
			.orderByDesc(Coupon::getId)
		);
		return R.data(CouponWrapper.build().pageVO(page, getUser().getUserId()));
	}

    @GetMapping("/user/page")
    @ApiOperation(value = "我的优惠券", notes = "")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "status", dataType = "string", value = "0未使用 1已使用 2已失效"),
	})
    public R<IPage<CouponUser>> userPage(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		IPage<CouponUser> page = couponUserService.page(Condition.getPage(query), Wrappers.<CouponUser>query().lambda()
			.eq(CouponUser::getUserId, getUser().getUserId()).orderByDesc(CouponUser::getId)
			.eq(ObjectUtil.isNotEmpty(params.get("status")), CouponUser::getStatus, params.get("status"))
		);
        return R.data(page);
    }

	@PostMapping("/receive")
	@ApiOperation(value = "领取优惠券", notes = "传入优惠券id")
	public R receive(@Valid @RequestBody CouponDTO.ReceiveDTO receiveDTO) {
		return R.status(couponService.receiveCoupon(receiveDTO.getId(), getUser().getUserId(), 1));
	}

	@GetMapping("/newcomer")
	@ApiOperation(value = "获取新人优惠券弹窗", notes = "")
	public R<List<Coupon>> newcomer() {
		User user = userService.getById(getUser().getUserId());
		if(DateUtil.isSameDay(new Date(), user.getCreateTime())){
			ConfigDTO.CouponDTO couponDTO = ConfigCache.getObject(ConfigKeys.NEWCOMER_COUPON, ConfigDTO.CouponDTO.class);
			couponDTO.getCouponList().forEach(item -> {
				Coupon coupon = couponService.getById(item.getId());
				if(ObjectUtil.isNotEmpty(coupon) && coupon.getStatus() == 1 && coupon.getLastTotal() > 0){
					int count = couponUserService.isGet(coupon.getId(), user.getId());
					if(count == 0){
						couponService.receiveCoupon(coupon.getId(), user.getId(), 1);
					}
				}
			});
			return R.data(couponDTO.getCouponList());
		}
		return R.data(new ArrayList<>());
	}

	@GetMapping("/birthday")
	@ApiOperation(value = "获取生日优惠券弹窗", notes = "")
	public R<List<Coupon>> birthday() {
		User user = userService.getById(getUser().getUserId());
		if(ObjectUtil.isNotEmpty(user.getBirthday()) && DateUtil.isSameDay(new Date(), user.getBirthday())){
			ConfigDTO.CouponDTO couponDTO = ConfigCache.getObject(ConfigKeys.BIRTHDAY_COUPON, ConfigDTO.CouponDTO.class);
			couponDTO.getCouponList().forEach(item -> {
				Coupon coupon = couponService.getById(item.getId());
				if(ObjectUtil.isNotEmpty(coupon) && coupon.getStatus() == 1 && coupon.getLastTotal() > 0){
					int count = couponUserService.isGet(coupon.getId(), user.getId());
					if(count == 0){
						couponService.receiveCoupon(coupon.getId(), user.getId(), 1);
					}
				}
			});
			return R.data(couponDTO.getCouponList());
		}
		return R.data(new ArrayList<>());
	}

}
